#include <TinyGPS.h>

#include <WString.h>
#include <NewSoftSerial.h>
#include <stdlib.h>

//NewSoftSerial GPS(8,9);
NewSoftSerial SD(7,6);
TinyGPS gps;
float flon, flat,fspeed,falt,fhead; //floating point: longitude, latitude, speed, altitude, heading
float last_flon, last_flot, last_alt;
boolean stopped;
int yr;
byte mon,day,hr,mn,sec,sec_h; //month, day, hour, minute, sec, 1/100 seconds
byte last_sec;
unsigned long fixAge;
int GPS_pwr=4;
int stop_count=0;
int LED_GPS=13;
int SD_pwr=5;
int LED_write=12;
int VSS=0;

void setup(){
  //GPS.begin(4800);
  SD.begin(9600);
  Serial.begin(4800);
  pinMode(LED_GPS,OUTPUT);
  pinMode(SD_pwr,OUTPUT);
  pinMode(GPS_pwr,OUTPUT);
  pinMode(LED_write,OUTPUT);
  digitalWrite(SD_pwr,HIGH);
  digitalWrite(GPS_pwr,LOW);
  digitalWrite(LED_write,LOW);
  
  delay(3000);
    SD.print("Year\tMonth\tDay\tHour\tMinute\tSeconds\t");
    SD.print("latitude\tLongitude\tAltitude\tSpeed(MPH)\tHeading\tVoltage");
    SD.println();
}

void loop(){
  digitalWrite(LED_GPS,LOW);
  VSS = map(analogRead(0),0,1024,0,15639);
  while(Serial.available()){
    int _c = Serial.read();
    //Serial.print(_c,BYTE);
    if(gps.encode(_c)){
      digitalWrite(LED_GPS,HIGH);
      gps.crack_datetime(&yr,&mn,&day,&hr,&mon,&sec,&sec_h);
      gps.f_get_position(&flat,&flon,&fixAge);
      fspeed=gps.f_speed_mph();
      falt=gps.f_altitude();
      fhead=gps.f_course();
      
      if(gps.speed()<=40){
        stopped=true;
      }else{
        stopped=false;
      }
      
      if(sec!=last_sec){      
        if(stopped){stop_count++;}
        if(!stopped || stop_count > 20){
          writeData();
          last_sec=sec;
          stop_count=0;
        }
      }
      digitalWrite(LED_GPS,LOW);
    }
  }
}

void writeData(){
  digitalWrite(LED_write,HIGH);
  SD.print(yr,DEC);
  SD.print("\t");
  SD.print(mn,DEC);
  SD.print("\t");
  SD.print(day,DEC);
  SD.print("\t");

  SD.print(hr,DEC);
  SD.print("\t");
  SD.print(mon,DEC);
  SD.print("\t");
  SD.print(sec,DEC);
  SD.print(".");
  SD.print(sec_h,DEC);
  SD.print("\t");
  SD.print(flat,5);
  SD.print("\t");
  SD.print(flon,5);
  SD.print("\t");
  SD.print(falt,2);
  SD.print("\t");
  SD.print(fspeed,2);
  SD.print("\t");
  SD.print(fhead,2);
  SD.print("\t"); 
  SD.print(VSS/1000,DEC);
  SD.print(".");
  SD.print(VSS%1000,DEC);
  SD.print("\t");
  SD.println();
  digitalWrite(LED_write,LOW);
}
